package com.gframework.core.middleware;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;

/**
 * 可拦截的Redirect策略操作类.
 * <p>
 * 本类在重定向基础上提供了一个拦截操作，并且可以再HttpClient执行execute的时候进行设置拦截方法。
 * 
 * @since 1.0.0
 * @author Ghwolf
 * 
 * @see CustomRedirectHttpClientWrapper
 */
class CustomRedirectStrategy extends DefaultRedirectStrategy {
	
	private final ThreadLocal<HttpRedirectInterceptor> threadLocal = new ThreadLocal<>();
	
	public CustomRedirectStrategy() {
		super(new String[] {"GET","POST","HEAD","DELETE","PUT","PATCH"});
	}

	@Override
	public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
			throws ProtocolException {
		boolean flag = super.isRedirected(request, response, context);
		HttpRedirectInterceptor interceptor = threadLocal.get();
		return interceptor != null && (flag || !interceptor.interceptorIfTrue())
				? interceptor.isRedirect(request, response, context, flag) : flag;
	}

	@Override
	public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
			throws ProtocolException {
		HttpRedirectInterceptor interceptor = threadLocal.get();
		if (interceptor != null) {
			HttpUriRequest req = interceptor.getRedirect(request, response, context);
			if (req != null) return req ;
		}
		return super.getRedirect(request, response, context);
	}
	
	void clear() {
		this.threadLocal.remove();
	}

	void set(HttpRedirectInterceptor interceptor) {
		this.threadLocal.set(interceptor);
	}

}
